package com.lagou.service.common;


import com.lagou.service.seriallzer.JSONSerializer;
import com.lagou.service.seriallzer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @date 2020/7/5 17:30
 * 自定义解码器
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> genericClass, JSONSerializer jsonSerializer) {
        this.clazz = genericClass;
        this.serializer = jsonSerializer;
    }


    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        out.add(serializer.deserialize(clazz, data));
    }
}
